package com.minelx.serverandclient.chatting;

import com.minelx.serverandclient.connector.ITubes;
import com.minelx.serverandclient.connector.PacketTubes;
import com.minelx.serverandclient.stream.data.Packet;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ChattingForm implements Closeable {
	private final ExecutorService executorService;
	private JPanel panel1;
	private JTextField messageTextField;
	private JButton sendMessageButton;
	private JList<Packet> messageListForm;
	private final DefaultListModel<Packet> messageListModel;
	private final PacketTubes tubes;

	public ChattingForm(ITubes tubes) {
		executorService = Executors.newSingleThreadExecutor();
		messageListModel = new DefaultListModel<>();
		messageListForm.setModel(messageListModel);
		this.tubes = new PacketTubes(tubes);
		sendMessageButton.addActionListener(this::sendMessage);
		executorService.submit(this::receivingMessage);
	}

	@Override
	public void close() {
		tubes.close();
		System.out.println("tubes has closed.");

		System.out.println("shutdownNow!!!");
		executorService.shutdownNow();
	}

	private void sendMessage(ActionEvent e) {
		tubes.send(Packet.of(messageTextField.getText()));
	}

	private void receivingMessage() {
		while (!Thread.interrupted()) {
			messageListModel.addElement(tubes.receive());
		}
	}

	public JPanel getPanel1() {
		return panel1;
	}
}
